<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<script>
class Player {
  constructor(name, teamColor) {
    this.partners = []; // 队友列表
    this.enemies = []; // 敌人列表
    this.state = 'live'; // 玩家状态
    this.name = name; // 角色名字
    this.teamColor = teamColor; // 队伍颜色
  }
  win() {
    console.log(this.name + ' won');
  }
  lose() {
    console.log(this.name + ' lost');
  }
  // 若队友全部死亡，则游戏失败
  die() {
    let all_dead = true;
    this.state = 'dead'; // 设置玩家状态为死亡
    for(let partner of this.partners) {
      if(partner.state !== 'dead') {
        all_dead = false;
        break;
      }
    }
    if(all_dead) {
      this.lose();
      for(let partner of this.partners) {
        partner.lose();
      }
      for(let enemy of this.enemies) {
        enemy.win()
      }
    }
  }
}
// 保存所有玩家
let players = [];
// 定义工厂函数创建玩家
let playerFactory = (name, teamColor) => {
  let newPlayer = new Player(name, teamColor); // 创建新玩家
  for(let player of players) {
    if(player.teamColor === newPlayer.teamColor) {
      player.partners.push(newPlayer);
      newPlayer.partners.push(player);
    } else {
      player.enemies.push(newPlayer);
      newPlayer.enemies.push(player);
    }
  }
  players.push(newPlayer);
  return newPlayer;
}

let player1 = playerFactory('皮蛋', 'red')
let player2 = playerFactory('瘦肉', 'red')
let player3 = playerFactory('荔湾', 'red')
let player4 = playerFactory('艇仔', 'red')

let player5 = playerFactory('皮蛋1', 'blue')
let player6 = playerFactory('瘦肉1', 'blue')
let player7 = playerFactory('荔湾1', 'blue')
let player8 = playerFactory('艇仔1', 'blue')

player1.die()
player2.die()
player3.die()
player4.die()

</script>
</body>
</html>